package com.ray.realm;

import com.ray.entity.Account;
import com.ray.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户信息
        Subject subject = SecurityUtils.getSubject();
        //principal登录时存入的用户信息，可直接获取
        Account account = (Account)subject.getPrincipal();

        //设置角色
        Set<String> roles = new HashSet<>();
        roles.add(account.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        //设置权限
        info.addStringPermission(account.getPerms());

        return info;
    }

    /**
     * 认证
     * 登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户携带的token，客户端将user信息封装到token
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //或者
//        String username = (String) authenticationToken.getPrincipal();
        //用户名验证，是否存在
        Account account = accountService.findByUsername(token.getUsername());
        if(account!=null){
            //shiro密码验证，是否正确
            //account登录成功存入Subject中Object principal
//            return new SimpleAuthenticationInfo(account,account.getPassword(),getName());
            //shiro密码验证，有盐，是否正确
            return new SimpleAuthenticationInfo(account,account.getPassword(), ByteSource.Util.bytes(account.getSalt()),getName());
        }
        return null;
    }
}
